package utils;

import book.PairofUidAndBookId;
import com.bit.utils.FileUtils;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-07-11
 * Time: 15:06
 */
public class AnalyzingBorrowedBook {
    public void storeObject(PairofUidAndBookId[] pairofUidAndBookIds, String filename)throws IOException {
        int booksUseLen = 0;
        for (int i = 0; i < pairofUidAndBookIds.length ; i++) {
            if(pairofUidAndBookIds[i] != null){
                booksUseLen++;
            }
        }
        StringBuilder jsonAraay = new StringBuilder();//StringBuilder可以修改字符串的内容，也就是这个对象可以修改，但是String不行
        for (int i = 0; i < booksUseLen; i++) {
            jsonAraay.append(pairofUidAndBookIds[i].toJson());
            if(i != booksUseLen - 1){ //字符串以\n为分隔符存入文件(方便以分隔符读取)，最后一行字符串不用存储\n
                jsonAraay.append("\n");
            }
        }
        FileUtils.writeFile(jsonAraay.toString(), filename);  //这里用文件写入方法，并且把字符串转入String(不可修改)写入文件
    }
    public PairofUidAndBookId[] loadObject(String filename) throws IOException{
        String content = FileUtils.readFile(filename);
        if(content == null || content.isEmpty()){
            System.out.println("已借阅书籍列表无数据，表示没有用户借阅过书籍");
            return null;
        }
        String[] JsonStrings = content.split("\n"); //以\n分割存入到各个对象
        PairofUidAndBookId[] pairofUidAndBookIds =  new PairofUidAndBookId[JsonStrings.length];
        for (int i = 0; i < JsonStrings.length; i++) {
//            String[] uidAndBookIds = JsonStrings[i].split(",");   //等待测试
//            pairofUidAndBookIds[i].setUserId(Integer.parseInt(uidAndBookIds[0]));
//            pairofUidAndBookIds[i].setBookId(Integer.parseInt(uidAndBookIds[1]));
            PairofUidAndBookId pairofUidAndBookId = new PairofUidAndBookId();
            String[] uidAndBookIds = JsonStrings[i].split(",");
            pairofUidAndBookId.setUserId(Integer.parseInt(uidAndBookIds[0]));
            pairofUidAndBookId.setBookId(Integer.parseInt(uidAndBookIds[1]));

            pairofUidAndBookIds[i] = pairofUidAndBookId;
        }
        return pairofUidAndBookIds;
    }
}
